#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import json
import shutil
import sys

# 导入日志模块
from logger import app_logger as logger

# 定义常量
TEMP_DIR = 'temp'
ACCOUNTS_FILE = os.path.join(TEMP_DIR, 'accounts.json')
USER_DATA_ROOT = os.path.join(TEMP_DIR, 'user_data')
KEEP_PORT = 9222  # 要保留的端口号

# 定义账号必要字段和可选字段
REQUIRED_FIELDS = ['user_id', 'nickname', 'is_logged', 'port']
OPTIONAL_FIELDS = ['avatar', 'keywords', 'replies', 'red_id']

def validate_account(account_data):
    """验证账号数据是否包含所有必要字段"""
    for field in REQUIRED_FIELDS:
        if field not in account_data:
            return False
    return True

def main():
    # 检查accounts.json是否存在
    if not os.path.exists(ACCOUNTS_FILE):
        print(f"错误: {ACCOUNTS_FILE} 文件不存在")
        return

    # 读取accounts.json
    try:
        with open(ACCOUNTS_FILE, 'r', encoding='utf-8') as f:
            accounts = json.load(f)
    except Exception as e:
        print(f"读取 {ACCOUNTS_FILE} 出错: {e}")
        return

    # 检查是否为数组格式
    if not isinstance(accounts, list):
        print(f"错误: {ACCOUNTS_FILE} 不是数组格式")
        return

    # 检查要保留的端口号是否存在
    keep_port_exists = False
    for account in accounts:
        if account.get('port') == KEEP_PORT:
            keep_port_exists = True
            break

    if not keep_port_exists:
        print(f"错误: 要保留的端口 {KEEP_PORT} 不在 {ACCOUNTS_FILE} 中")
        return

    # 删除无效账号（缺少必要字段）
    valid_accounts = []
    invalid_count = 0

    for account in accounts:
        if not validate_account(account):
            missing_fields = [field for field in REQUIRED_FIELDS if field not in account]
            logger.warning(f"账号缺少必要字段: {', '.join(missing_fields)}")
            invalid_count += 1
        elif 'user_id' not in account:
            # 兼容旧代码，确保user_id检查仍然存在
            logger.warning(f"账号缺少user_id字段")
            invalid_count += 1
        else:
            valid_accounts.append(account)

    if invalid_count > 0:
        print(f"找到 {invalid_count} 个无效账号（缺少必要字段）")

        # 保存更新后的accounts.json
        try:
            with open(ACCOUNTS_FILE, 'w', encoding='utf-8') as f:
                json.dump(valid_accounts, f, ensure_ascii=False, indent=2)
            print(f"已成功删除 {invalid_count} 个无效账号并更新 {ACCOUNTS_FILE}")
        except Exception as e:
            print(f"保存 {ACCOUNTS_FILE} 出错: {e}")
    else:
        print("没有找到无效账号，所有账号都包含必要字段")

    # 获取所有有效的user_id
    valid_user_ids = set()
    for account in valid_accounts:
        if 'user_id' in account:
            valid_user_ids.add(account['user_id'])

    print(f"找到 {len(valid_user_ids)} 个有效的user_id")

    # 检查user_data目录是否存在
    if not os.path.exists(USER_DATA_ROOT):
        print(f"错误: {USER_DATA_ROOT} 目录不存在")
        return

    # 获取user_data目录下的所有目录
    all_dirs = [d for d in os.listdir(USER_DATA_ROOT) if os.path.isdir(os.path.join(USER_DATA_ROOT, d))]
    print(f"找到 {len(all_dirs)} 个目录")

    # 删除不是要保留端口的目录
    deleted_dirs = 0
    keep_dir = f"port_{KEEP_PORT}"

    for dir_name in all_dirs:
        if dir_name != keep_dir:
            dir_path = os.path.join(USER_DATA_ROOT, dir_name)
            try:
                shutil.rmtree(dir_path)
                print(f"已删除目录: {dir_path}")
                deleted_dirs += 1
            except Exception as e:
                print(f"删除目录 {dir_path} 失败: {e}")

    print(f"总共删除了 {deleted_dirs} 个目录")
    print("清理完成!")

    # 确保输出立即显示
    sys.stdout.flush()

if __name__ == "__main__":
    main()